""" CookieJar module """
import os
from PyQt4.QtNetwork import QNetworkCookieJar, QNetworkCookie

class CookieJar (QNetworkCookieJar):
    """ persistend CookieJar """

    def __init__(self, 
            parent=None, 
            filename=None, 
            safeSessionCookies=True
        ):
        super(CookieJar, self).__init__(parent)
        #: path to file where cookies are save to or loaded from
        self.filename = filename 
        #: save session cookies (True|False)
        self.safeSessionCookies = safeSessionCookies 


    def save(self):
        """ save cookies to file if CookieJars filename is set """
        if self.filename:
            with open(self.filename, "w+") as f:
                for c in self.allCookies():
                    if self.saveSessionCookies or not c.isSessionCookie(): 
                        f.write(str(c.toRawForm())+"\n")
            


    def load(self):
        """ load from file if CookieJars filename is set """
        cookies = []
        if self.filename and os.path.exists(self.filename):
            with open(self.filename, "r+") as f:
                for cookie in f:
                    cs = QNetworkCookie.parseCookies(cookie)
                    for c in cs:
                        cookies.append(c)
        self.setAllCookies(cookies)




